#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int get_strsep_segment_by_index(char *string, char *delim, int index, char *segment) {
    char *s = strdup(string);
    char *token = NULL;
    int count = 0;

    printf("dbg---> string=[%s], delim=[%s], index=[%d]\n", string, delim, index);
    for(token = strsep(&s, delim); token != NULL; token = strsep(&s, delim)) {
        printf("dbg---> token=[%s]\n", token);
		if(!strcmp(token, ""))
            continue;
	
        count++;
		printf("dbg---> count=[%d]\n", count);
        if(count == index)
            sprintf(segment, "%s", token);
    }
    printf("dbg---> return count=[%d]\n", count);
    return count;
}

int second_return(char *string, char *delim, int index, char *segment)
{
	return get_strsep_segment_by_index(string, delim, index, segment);
}

void main(int argc, char **argv)
{
    //char string[] = "eth2.1 eth2.2 eth2.3 eth2.4 ra0 rai0";  
    char string[] = "eth2.1;;eth2.3;;ra0;rai0";  
    //char string[] = "";  
    //char delim[] = " ";
    char delim[] = ";";
	char segment[16] = {0};
	#define MIN_IDX 1
	#define MAX_IDX 6
	int idx;
	int count = 0;

	//count = get_strsep_segment_by_index(string, delim, -1, NULL);
	count = second_return(string, delim, -1, NULL);
	printf("count is [%d]\n", count);
#if 0
	for(idx = 1; idx <= count; idx++){
		get_strsep_segment_by_index(string, delim, idx, segment);
		printf("idx %d segment is [%s]\n", idx, segment);
	}
#endif
}

/*
int get_strsep_segment_by_index(char *string, char *delim, int index, char *segment) {  
    char *s = strdup(string);
    char *token = NULL;
	int count = 0;

    for(token = strsep(&s, delim); token != NULL; token = strsep(&s, delim)) {
		if(!strcmp(token, ""))
			continue;

		count++;
		if(count == index)
			sprintf(segment, "%s", token);
    }

    return count;
}
*/
